<template>
    <div id="song_list">
        <div class="container">
            <div class="handle-box">
                <el-form ref="form" :inline="true" :model="form">
                    <el-form-item label="">
                        <el-input
                            placeholder="ID"
                            clearable
                            @keyup.native.enter="handleSearch"
                            v-model="query.songId"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            clearable
                            @keyup.native.enter="handleSearch"
                            v-model="query.songName"
                            placeholder="歌曲名"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            clearable
                            @keyup.native.enter="handleSearch"
                            v-model="query.actorName"
                            placeholder="歌手名"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            clearable
                            @keyup.native.enter="handleSearch"
                            v-model="query.albumName"
                            placeholder="专辑名"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-input
                            clearable
                            @keyup.native.enter="handleSearch"
                            v-model="query.isrc"
                            placeholder="ISRC"
                            class="handle-input mr10"
                        ></el-input>
                    </el-form-item>

                    <el-form-item label="">
                        <el-select
                            @change="handleSearch"
                            v-model="query.auditFreeStatus"
                            placeholder="版权状态"
                            :clearable="true"
                            class="handle-select mr10"
                        >
                            <el-option key="0" label="未上传版权" :value="0"></el-option>
                            <el-option key="1" label="版权待审核" :value="1"></el-option>
                            <el-option key="2" label="版权审核不通过" :value="2"></el-option>
                            <el-option key="-1" label="退回修改" :value="-1"></el-option>
                            <el-option key="4" label="版权审核通过" :value="4"></el-option>
                            <el-option key="-2" label="重提待审" :value="-2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button :disabled="disabled" type="primary" @click="handleSearch">
                            <!-- 查询 -->
                            {{ $t('m.queryBtn') }}
                        </el-button>
                    </el-form-item>
                </el-form>
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>

                <el-table-column width="auto" label="ID" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.songId }}</template>
                </el-table-column>

                <el-table-column width="auto" label="歌曲名" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.songName }}</template>
                </el-table-column>

                <el-table-column width="auto" label="歌手名" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.actorName }}</template>
                </el-table-column>

                <el-table-column width="auto" label="专辑名" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.albumName }}</template>
                </el-table-column>

                <el-table-column width="auto" label="ISRC" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.isrc }}</template>
                </el-table-column>

                <el-table-column width="auto" label="版权状态" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">
                        <a href="javascript:void(0)" class="btn" v-if="scope.row.auditFreeStatus == 0 || scope.row.auditFreeStatus == -2">
                            上传版权证明
                            <input type="file" id="file" accept=".zip,.rar" name="file" @change="uploadFile($event, scope.row)" />
                        </a>
                        <span v-if="scope.row.auditFreeStatus == 1">版权待审核</span>

                        <!-- <span v-if="scope.row.auditFreeStatus == -1">退回修改</span> -->
                        <span v-if="scope.row.auditFreeStatus == 4">版权审核通过</span>
                        <span v-if="scope.row.auditFreeStatus == -2">重提待审</span>
                    </template>
                </el-table-column>

                <el-table-column width="auto" label="审核结果" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{
                        scope.row.checkStatus == 1
                            ? '待审核 '
                            : scope.row.checkStatus == 2
                            ? '审核不通过'
                            : scope.row.checkStatus == -1
                            ? '退回修改'
                            : scope.row.checkStatus == 4
                            ? '审核通过'
                            : scope.row.checkStatus == 6
                            ? '音源审核通过'
                            : scope.row.checkStatus == 5
                            ? '产品上线'
                            : scope.row.checkStatus == -2
                            ? '重提待审'
                            : scope.row.checkStatus == 0
                            ? '回退'
                            : scope.row.checkStatus == -9
                            ? '产品下线'
                            : ''
                    }}</template>
                </el-table-column>

                <el-table-column width="auto" label="创建时间" align="center" :show-overflow-tooltip="true">
                    <template slot-scope="scope">{{ scope.row.createTime }}</template>
                </el-table-column>

                <el-table-column width="auto" label="版权管理" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="warning"
                            size="mini"
                            v-if="scope.row.checkStatus == 1 && scope.row.auditFreeStatus == 1"
                            @click="handleChecked(scope.$index, scope.row)"
                            >审核</el-button
                        >
                        <!-- <el-button type="warning" size="mini" class="red" @click="handleDelete(scope.$index, scope.row)">审核</el-button> -->
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 30]"
                    @size-change="handleSizeChange"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <el-dialog title="审核界面" :visible.sync="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="auto" :rules="rules">
                <el-form-item label="歌曲名">
                    <el-input v-model="form.songName" disabled></el-input>
                </el-form-item>

                <el-form-item label="歌手名">
                    <el-input v-model="form.actorName" disabled></el-input>
                </el-form-item>

                <el-form-item label="" class="upload-file">
                    <p>文件</p>
                </el-form-item>
                <el-form-item class="upload-excel" label="版权证明：">
                    <el-input
                        class=""
                        style="width: 50%"
                        placeholder="显示上传的文件名"
                        clearable
                        disabled
                        v-model="form.copyrightName"
                    ></el-input>
                    <img src="" alt="" />
                    <a href="javascript:void(0)" class="btn" style="margin-left: 20px">
                        下载
                        <input type="file" id="file" name="file" @click.prevent="getKey(form.copyrightName)" />
                    </a>
                </el-form-item>

                <el-form-item label="" class="upload-file">
                    <p>审核信息</p>
                </el-form-item>
                <el-form-item class="upload-excel" label="审核结果:" prop="checkStatus">
                    <el-select v-model="form.checkStatus" @change="handleSearch" placeholder="" :clearable="true" style="width: 100%">
                        <!-- <el-option key="1" label="待审核" :value="1"></el-option> -->
                        <el-option key="2" label="版权审核不通过" :value="2"></el-option>
                        <!-- <el-option key="-1" label="退回修改" :value="-1"></el-option> -->
                        <el-option key="4" label="版权审核通过" :value="4"></el-option>
                        <!-- <el-option key="6" label="音源审核通过" :value="6"></el-option>
                        <el-option key="5" label="产品上线" :value="5"></el-option>
                        <el-option key="-2" label="重提待审" :value="-2"></el-option>
                        <el-option key="0" label="回退" :value="0"></el-option>
                        <el-option key="-9" label="产品下线" :value="-9"></el-option> -->
                    </el-select>
                </el-form-item>

                <!-- <el-form-item class="upload-excel" label="版权状态：" prop="auditFreeStatus">
                    <el-select @change="handleSearch" v-model="form.auditFreeStatus" placeholder="" :clearable="true" style="width: 100%;">
                        <el-option key="0" label="未上传版权" :value="0"></el-option>
                        <el-option key="1" label="版权待审核" :value="1"></el-option>
                        <el-option key="-1" label="退回修改" :value="-1"></el-option>
                        <el-option key="4" label="版权审核通过" :value="4"></el-option>
                        <el-option key="-2" label="重提待审" :value="-2"></el-option>
                    </el-select>
                </el-form-item> -->
                <el-form-item class="upload-excel" label="备注：">
                    <el-input class="" style="width: 100%" clearable v-model="form.remark"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveChecked">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
  import NProgress from 'nprogress';
  import { debounce, throttle } from '@/utils/utils.js';
  export default {
      name: 'SongList',
      data() {
          return {
              disabled: false,
              rules: {
                  checkStatus: [{ required: true, message: '请选择审核状态', trigger: 'change' }]
                  // auditFreeStatus: [{ required: true, message: '请选择版权状态', trigger: 'change' }]
              },
              query: {
                  songId: '',
                  songName: '',
                  actorName: '',
                  albumName: '',
                  isrc: '',
                  auditFreeStatus: '',
                  pageIndex: 1,
                  pageSize: 10
              },
              editVisible: false,
              tableData: [],
              pageTotal: 0,
              form: {
                  id: '',
                  songName: '',
                  actorName: '',
                  // auditFreeStatus: '',
                  checkStatus: '',
                  copyrightName: '',
                  jobCode: '',
                  remark: ''
              }
          };
      },
      activated() {
          this.getData();
      },
      methods: {
          async saveChecked() {
              try {
                  let url = '/job/copyRight';
                  let { data: res } = await this.$http[1].get(url, {
                      params: this.$removeField({
                          id: this.form.id,
                          // songName: this.form.songName,
                          // actorName: this.form.actorName,
                          // auditFreeStatus: this.form.auditFreeStatus,
                          checkStatus: this.form.checkStatus,
                          // copyrightName: this.form.copyrightName,
                          jobCode: this.form.jobCode,
                          remark: this.form.remark
                      })
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log(res);
                  this.editVisible = false;
                  this.$message.success({
                      duration: 1500,
                      message: res.message
                  });
                  this.getData();
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          async getKey(filename) {
              try {
                  // NProgress.start();
                  let url = '/job/musicRight';
                  let { data: res } = await this.$http[1].post(
                      url,

                      `jobCode=${this.form.jobCode}`,
                      // jobCode: '107021041918463714313097'
                      {
                          headers: {
                              // responseType: 'blob',
                              'Content-Type': 'application/x-www-form-urlencoded'
                          }
                      }
                  );
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log(res);
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  this.downFile(filename, res.data);

                  this.editVisible = false;
                  // NProgress.done();
              } catch (err) {
                  console.dir(err);
                  this.editVisible = false;
                  // NProgress.done();
              }
          },
          async downFile(filename, key) {
              try {
                  NProgress.start();
                  let { data: res } = await this.$http[1].get(`/download/${key}`, {
                      params: {},
                      responseType: 'blob'
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log(res);
                  let link = document.createElement('a');
                  let blob = new Blob([res], { type: 'application/x-zip-compressed' });
                  link.style.display = 'none';
                  link.href = URL.createObjectURL(blob);
                  link.setAttribute('download', filename + '.zip');
                  document.body.appendChild(link);
                  link.click();
                  document.body.removeChild(link);
                  NProgress.done();
              } catch (err) {
                  console.dir(err);
                  NProgress.done();
              }
          },
          uploadFile(e, row) {
              console.log(e, row);
              this.$http[1]
                  .get('/job/getcode', {
                      params: this.$removeField({
                          jobId: row.jobId
                      })
                  })
                  .then(({ data: res }) => {
                      console.log(res);
                      this.upload(e, row, res.data);
                  });
          },
          async upload(e, row, jobCode) {
              try {
                  NProgress.start();
                  var event = e || window.event;
                  var target = event.target || e.srcElement;
                  var file = target.files[0];
                  this.query.src = this.$getObjectURL(file);
                  var formdata = new FormData();
                  formdata.append('musicRight', file);
                  formdata.append('id', row.id);
                  formdata.append('jobCode', jobCode);
                  let url = '/job/uploadMusicRight';
                  let headers = {
                      'Content-Type': 'multipart/form-data'
                  };
                  if (localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')) {
                      headers['cppname'] = encodeURIComponent(localStorage.getItem('ms_username'));
                  }
                  let { data: res } = await this.$http[1].post(url, formdata, {
                      // headers: {
                      //     'Content-Type': 'multipart/form-data',
                      //     cppname:
                      //         localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')
                      //             ? localStorage.getItem('ms_username')
                      //             : null
                      // }
                      headers
                  });
                  console.log('响应数据', res);
                  target.value = null;
                  this.$message.success({
                      message: res.message,
                      duration: 1500
                  });
                  this.getData();
                  NProgress.done();
              } catch (err) {
                  console.dir(err);
                  NProgress.done();
                  target.value = null;
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          handleChecked(index, row) {
              this.editVisible = true;

              this.getCheckedData(row.id);
              // this.$router.replace({
              //     path: '/warehouse_/details',
              //     query: {
              //         id: row.id
              //     }
              // });
          },

          async getCheckedData(id) {
              try {
                  let url = '/job/songExamine';
                  let { data: res } = await this.$http[1].get(url, {
                      params: this.$removeField({
                          id
                      })
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log(res);
                  let { songName, actorName, auditFreeStatus, checkStatus, copyrightName, jobCode, remark } = res.data;
                  this.form = { songName, actorName, auditFreeStatus, checkStatus: '', copyrightName, jobCode, remark, id };
              } catch (err) {
                  console.dir(err);
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          async getData() {
              try {
                  NProgress.start();
                  this.disabled = true;
                  let url = '/job/details';
                  let headers = {};
                  if (localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')) {
                      headers['cppname'] = encodeURIComponent(localStorage.getItem('ms_username'));
                  }
                  let { data: res } = await this.$http[1].get(url, {
                      params: this.$removeField({
                          page: this.query.pageIndex,
                          size: this.query.pageSize,
                          songId: this.query.songId.trim() != '' ? parseInt(this.query.songId.trim()) : '',
                          songName: this.query.songName.trim(),
                          actorName: this.query.actorName.trim(),
                          albumName: this.query.albumName.trim(),
                          isrc: this.query.isrc.trim(),
                          auditFreeStatus: this.query.auditFreeStatus
                      }),
                      // headers: {
                      //     cppname:
                      //         localStorage.getItem('roles') && JSON.parse(localStorage.getItem('roles')).includes('CPOA')
                      //             ? localStorage.getItem('ms_username')
                      //             : null
                      // }
                      headers
                  });
                  if (res.code != '0000') {
                      throw new Error(res.message);
                  }
                  console.log('歌曲列表', res);
                  if (res.data.content && res.data.content.length > 0) {
                      res.data.content.map((item) => {
                          item.createTime = this.$dateFormat(item.createTime, '', '-');
                      });
                      this.tableData = res.data.content;
                      this.pageTotal = res.data.totalElements;
                  } else {
                      this.tableData = [];
                      this.pageTotal = 0;
                  }
                  NProgress.done();
                  this.disabled = false;
              } catch (err) {
                  console.log(err);
                  NProgress.done();
                  this.disabled = false;
                  this.$message.error({
                      message: err.message,
                      duration: 1500
                  });
              }
          },
          // 触发搜索按钮
          // handleSearch() {
          //     this.$set(this.query, 'pageIndex', 1);
          //     this.getData();
          // },

          handleSearch: debounce(function () {
              this.$set(this.query, 'pageIndex', 1);
              this.getData();
          }, 300),

          // 多选操作
          handleSelectionChange(val) {
              // this.multipleSelection = val;
          },

          // 分页导航
          handlePageChange(val) {
              this.$set(this.query, 'pageIndex', val);
              this.getData();
          },
          handleSizeChange(val) {
              this.$set(this.query, 'pageSize', val);
              this.getData();
          }
      }
  };
</script>

<style lang="scss">
  #song_list {
      // 防止表头换行
      .table-header {
          .cell {
              white-space: nowrap !important;
          }
      }
      .handle-box {
          margin-bottom: 20px;
          .el-form {
              display: grid;
              grid-auto-flow: column;
              justify-content: flex-start;
              .el-form-item {
                  width: 95%;
                  .el-form-item__content {
                      .el-select,
                      .handle-input {
                          width: 100%;
                      }
                  }
              }
          }
      }
      .btn {
          position: relative;
          display: inline-block;
          text-align: center;
          color: #fff;
          text-decoration: none;
          width: 80px;
          height: 32px;
          line-height: 32px;
          background: #409eff;
          border-radius: 3px;
          font-size: 12px;
          vertical-align: middle;
          // margin-left: 10px;
          input[name='file'] {
              opacity: 0;
              width: 100%;
              height: 100%;
              position: absolute;
              left: 0;
          }
      }

      .upload-file {
          // margin-top: 50px;
          .el-form-item__content {
              margin-left: 35px !important;
              p {
                  width: 100px;
                  height: 30px;
                  line-height: 30px;
                  background-color: rgba(0, 0, 0, 0.1);
                  text-align: center;
                  color: #333;
              }
          }
      }
      .upload-excel {
          padding-left: 10px;
          box-sizing: border-box;

          .el-form-item__label {
              width: 150px;
              text-align: right;
              font-size: 14px;
              color: #333;
          }
      }
      .handle-box {
          margin-bottom: 20px;
      }

      .handle-select {
          width: 120px;
      }

      .handle-input {
          /* width: 300px; */
          width: 69px;
          height: 28px;
          display: inline-block;
      }
      .table {
          width: 100%;
          font-size: 14px;
      }
      /* .red {
            color: #ff0000;
        } */
      .mr10 {
          margin-right: 10px;
      }
      .table-td-thumb {
          display: block;
          margin: auto;
          width: 40px;
          height: 40px;
      }
  }
</style>
